<!-- pages/login/components/mobile.vue -->
<script setup>
import { getCodeApi, loginByMobileApi } from '@/apis/user';
import { ref  } from 'vue'
import { useUserStore } from '@/stores/user'

const store = useUserStore()

// 1. 定义对象
const form = ref()
const isAgree = ref(false)
const formData = ref({
  mobile: '',
  code: ''
})
const rules = {
  mobile: {
    rules: [
      { required: true, errorMessage: '手机号不能为空' },
      { pattern: '^[1][3-9][0-9]{9}$', errorMessage: '手机号格式不正确' }
    ]
  },
  code: {
    rules: [
      { required: true, errorMessage: '验证码不能为空' },
      { pattern: '^[0-9]{6}$', errorMessage: '请输入6位数字验证码' }
    ]
  }
}

// 2. 倒计时处理
const showCountDown = ref(false)
const getMobileCode = async () => {
  try {
    // 1.1 校验手机号
    await form.value.validateField(['mobile'])

    const res =  await getCodeApi({mobile: formData.value.mobile, type: 'login'})
    formData.value.code = res.code

    // 1.2 开始倒计时
    showCountDown.value = true
  } catch (e) {
    console.log(e)
  }
}

// 3. 登录
const onSubmit = async ()=>{
  // 3.1 校验
  if(!isAgree.value) return uni.showToast({title: '请勾选同意协议', icon: 'none'})
  const data = await form.value.validate(['mobile'])

  // 3.2 调用接口
  const res = await loginByMobileApi(data)
  uni.showToast({title: '登录成功!'})
  
  // 3.3 存储token
  store.setToken(res.token)

  // 3.4 存储用户id
  store.setUserId(res.id)

  // 3.4 回跳到我的页面
  uni.switchTab({
    url: '/pages/my/index',
  })

}


</script>

<template>
  <uni-forms class="login-form" ref="form" :model-value="formData" :rules="rules">
    <uni-forms-item name="mobile">
      <uni-easyinput v-model="formData.mobile" :input-border="false" :clearable="false" placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5" />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput v-model="formData.code" :input-border="false" :clearable="false" placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5" />
      <text class="text-button" v-if="!showCountDown" @click="getMobileCode">获取验证码</text>
      <view class="text-button" v-else>
        <uni-countdown :show-day="false" :show-hour="false" :show-minute="false" :second="59"
          @timeup="showCountDown=false" />秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="isAgree = !isAgree" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
  </uni-forms>
</template>

<script>
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>

<style lang="scss">
@import './styles.scss';
</style>